/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bakenote.data;

import bakenote.core.RecipeGroup;
import org.apache.pivot.wtk.content.TreeBranch;
import org.apache.pivot.wtk.content.TreeNode;
import org.apache.pivot.wtk.media.Picture;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Iterator;

/**
 *
 * @author lello
 */
public class RecipeGroupList {

	// This array contains the list of all the formulae actually loaded
	// by the program. It is accessible in the entire program.
    private final static TreeBranch rootNode = new TreeBranch("ROOT");
    private final static TreeBranch myCollections = new TreeBranch("My Recipes");
    private static Picture treeIcon = null;

    private RecipeGroupList() {    }

    public static void init() {
        String imageName = "bakenote/ui/icons/folder.png";
        ClassLoader loader = RecipeGroupList.class.getClassLoader();
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(loader.getResource(imageName));
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        treeIcon = new Picture(bufferedImage);
        myCollections.setIcon(treeIcon);
        rootNode.add(myCollections);
    }

	public static TreeNode getNode(int i) {
		return myCollections.get(i);
	}

    public static void remove(RecipeGroup rg) {
        boolean found = false;
        Iterator<TreeNode> it = myCollections.iterator();
        while (!found && it.hasNext()) {
            TreeNode treeNode = it.next();
            if ( treeNode.getUserData().equals(rg) ) {
                found = true;
                myCollections.remove(treeNode);
            }
        }
    }

    public static RecipeGroup getGroup(int i) {
		return (RecipeGroup) myCollections.get(i).getUserData();
	}

    public static RecipeGroup getGroup(String uuid) throws Exception {
        boolean found = false;
        RecipeGroup rg = null;
        Iterator<TreeNode> it = myCollections.iterator();
        while (!found && it.hasNext()) {
           TreeNode treeNode = it.next();
           rg = (RecipeGroup) treeNode.getUserData();
           if (rg.getUUID().equals(uuid)) {
               found = true;
           }
        }
        if (rg != null) {
            return rg;
        } else {
            throw new Exception();
        }
    }

	public static void add(RecipeGroup rg) {
        TreeNode treeNode = new TreeNode(treeIcon,rg.getName());
        treeNode.setUserData(rg);
		myCollections.add(treeNode);
	}

	public static TreeBranch getGroupList() {
		return rootNode;
	}
}
